package com.smiier.skin;

import java.util.HashMap;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.pay.ali.AlipayListener;
import cn.o.app.pay.ali.AlipayTask;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.share.ShareWXUtils;
import com.evan.common.utils.DeviceUtility;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.UserExtra;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.AccountCheckPayPwdTask;
import com.smiier.skin.net.AccountCheckPayPwdTask.AccountCheckPayPwdRequest;
import com.smiier.skin.net.AccountCheckPayPwdTask.AccountCheckPayPwdResponse;
import com.smiier.skin.net.AccountGetTask;
import com.smiier.skin.net.AccountGetTask.AccountGetRequest;
import com.smiier.skin.net.AccountGetTask.AccountGetResponse;
import com.smiier.skin.net.AccountRechargeApplyTask;
import com.smiier.skin.net.AccountRechargeApplyTask.AccountRechargeApplyRequest;
import com.smiier.skin.net.AccountRechargeApplyTask.AccountRechargeApplyResponse;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalFormat;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.tencent.mm.sdk.constants.Build;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;

/**
 * @{# Cost2DoctorActivity.java Create on 2014-6-10 下午1:35:57
 * 
 * @author <a href="mailto:evan0502@qq.com">Evan</a>
 * @version 1.0 创建付费咨询
 */

@SuppressLint("InflateParams")
public class CostOrReward2DoctorActivity extends BasicActivity {

	private final String txt_yue = "余额支付（余额：%s元）",
			txt_chongzhi = "充值并支付剩余金额（%s元）";
	private final String txt_zhifubao = "使用支付宝支付%s元";
	private final String txt_weixin = "使用微信支付%s元";
	private final String txt_zhifubao_shengyu = "使用支付宝支付剩余%s元";
	private final String txt_weixin_shengyu = "使用微信支付剩余%s元";
	private final String txt_doctor = "%s医生_图文咨询";
	private CheckBox mCheck1;
	private CheckBox mCheck2;
	private CheckBox mCheck3;
	private TextView mUserYue;
	private TextView mOrderName;
	private TextView mOrderSerial;
	private TextView mOrderPrice;
	private double mYue;
	private double mAccountYue;
	// 问题id，如果不为空，则是创建问题成功后直接指派给某个医生
	String qid;
	private User mUser;
	private TextView mPayZhifubao;
	private TextView mPayWeixin;
	private TextView mPayYue;
	int mCostType = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent i = getIntent();
		UserExtra extra = new UserExtra();
		extra.getFrom(i);
		mUser = extra.getUser();
		if (mUser == null) {
			finish();
		}
		mYue = mUser.Cost;
		setContentView(R.layout.activity_cost_reward_2_doctor);
		init();
		setNavTitle("订单支付");
		mCheck1 = (CheckBox) findViewById(R.id.check_1);
		mCheck2 = (CheckBox) findViewById(R.id.check_2);
		mCheck3 = (CheckBox) findViewById(R.id.check_3);
		mUserYue = (TextView) findViewById(R.id.user_yue);
		mOrderName = (TextView) findViewById(R.id.order_type);
		mOrderSerial = (TextView) findViewById(R.id.order_serial_number);
		mOrderPrice = (TextView) findViewById(R.id.order_price);
		if (mUser.Name.contains("悬赏")) {
			mOrderName.setText("悬赏");
		} else {
			mOrderName.setText(String.format(txt_doctor, mUser.Name));
		}
		mPayZhifubao = (TextView) findViewById(R.id.pay_zhifubao);
		mPayWeixin = (TextView) findViewById(R.id.pay_weixin);
		mOrderPrice.setText("￥" + mUser.Cost);
		mPayYue = (TextView) findViewById(R.id.pay_yue);
		mPayWeixin.setOnClickListener(mListener);

	}

	@Override
	protected void onResume() {
		super.onResume();
		
//		MobclickAgent.onResume(this);
		AccountGetRequest req = new AccountGetRequest();
		req.token = GlobalSettings.sToken;
		AccountGetTask task = new AccountGetTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<AccountGetTask.AccountGetRequest, AccountGetTask.AccountGetResponse>() {
			@Override
			public void onException(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					Exception e) {

			}

			@Override
			public void onComplete(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					AccountGetResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				GlobalSettings.sYue = response.Res;
				String totalAccount = GlobalFormat
						.formatCNY(GlobalSettings.sYue);
				mAccountYue = Double.parseDouble(totalAccount);
				/*
				 * if(GlobalSettings.sYue<mUser.Cost){
				 * mCheck3.setEnabled(enabled); }
				 */
				// showbutton();
				mPayYue.setText(String.format(txt_yue, totalAccount));
				mUserYue.setText(String.format(txt_yue, totalAccount));
			}
		});
		add(task);
		mPayWeixin.setEnabled(true);
	}

	private OnClickListener mListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			mPayWeixin.setEnabled(false);
			if (GlobalSettings.mPwd == null
					|| GlobalSettings.mPwd.trim().equals("")) {
				getPwd(mCostType);
			} else {
				if (mCostType == 1) {
					payZhifubao();
				} else if (mCostType == 2) {
					payWeixin();
				} else if (mCostType == 3) {
					CommonUtility
							.finishActivityFromName(CreateQuestionSuccessfullyActivity.class
									.getSimpleName());
					Intent i = new Intent();
					setResult(0, i);
					finish();
				}
			}

		}
	};

	public void getPwd(final int mCostType) {
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						mPayWeixin.setEnabled(true);
						if (!CommonUtility.isNull(o)) {
							try {
								JSONObject object = (JSONObject) o;
								boolean isInit = object
										.getBoolean(Constant.JSON_PARAM_RES);
								if (isInit) {
									View v = LayoutInflater.from(activity)
											.inflate(R.layout.view_pay_page,
													null);
									final TextView code = (TextView) v
											.findViewById(R.id.code_error);
									TextView ok = (TextView) v
											.findViewById(R.id.button_ok);
									TextView cancel = (TextView) v
											.findViewById(R.id.button_cancel);
									TextView text_after_pay = (TextView) v
											.findViewById(R.id.text_after_pay);
									final EditText edit_pay_password = (EditText) v
											.findViewById(R.id.edit_pay_password);
									text_after_pay.setText("您即将用您的账户余额支付:"
											+ mUser.Cost + "元");
									final OAlert alert = new OAlert(
											getContext());
									alert.setTitle("请输入支付密码");
									alert.setContentView(v);
									alert.show();
									alert.setDismissListener(new OnDismissListener() {

										@Override
										public void onDismiss(
												DialogInterface dialog) {
											mPayWeixin.setEnabled(true);
										}
									});
									cancel.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View v) {
											alert.dismiss();
										}
									});
									ok.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View v) {
											code.setText("");
											final String password = edit_pay_password
													.getText().toString();
											if (!CommonUtility.isNull(password)) {
												HashMap<String, Object> params = new HashMap<String, Object>();
												params.put(
														Constant.PARAM_TOKEN,
														GlobalSettings.sToken);
												// params.put("Cost", mYue);
												params.put(Constant.PARAM_API,
														"Question.Set");
												params.put("PayPwd",
														OUtil.md5(password));
												AccountCheckPayPwdTask task = new AccountCheckPayPwdTask();
												AccountCheckPayPwdRequest req = new AccountCheckPayPwdRequest();
												req.token = GlobalSettings.sToken;
												req.paypwd = OUtil
														.md5(password);

												task.setRequest(req);
												task.addListener(new NetTaskListener<AccountCheckPayPwdTask.AccountCheckPayPwdRequest, AccountCheckPayPwdTask.AccountCheckPayPwdResponse>() {

													@Override
													public void onComplete(
															INetTask<AccountCheckPayPwdRequest, AccountCheckPayPwdResponse> task,
															AccountCheckPayPwdResponse response) {

														if (response != null
																&& response.ResultCode == 200) {
															alert.dismiss();
															if (mCostType == 1) {
																payZhifubao();
															} else if (mCostType == 2) {
																payWeixin();
															} else {
																Intent intent = new Intent(
																		Constant.RECIVER_QUESTION);
																intent.putExtra(
																		Constant.IDENTITY_KEY_1,
																		true);
																sendBroadcast(intent);
																OAlert alert = new OAlert(
																		getContext());
																alert.setOK("确认");
																alert.setTitle("支付成功");
																alert.show();
																GlobalSettings.mPwd = OUtil
																		.md5(password);
																alert.setListener(new OAlertListener() {

																	@Override
																	public boolean onOK(
																			OAlert alert) {

																		CommonUtility
																				.finishActivityFromName(CreateQuestionSuccessfullyActivity.class
																						.getSimpleName());
																		Intent i = new Intent();
																		setResult(
																				0,
																				i);
																		finish();

																		return false;
																	}

																	@Override
																	public boolean onCancel(
																			OAlert alert) {
																		return false;
																	}
																});
															}

														} else {
															toast(response.ResultMessage);
															code.setText(response.ResultMessage);
														}
													}

													@Override
													public void onException(
															INetTask<AccountCheckPayPwdRequest, AccountCheckPayPwdResponse> task,
															Exception e) {

													}
												});
												add(task);

											} else {
												Toast.makeText(
														CostOrReward2DoctorActivity.this,
														"请输入支付密码",
														Toast.LENGTH_SHORT)
														.show();
											}

										}
									});

								} else {
									if (CommonUtility
											.isNull(GlobalSettings.sUser.Mobile)) {
										OAlert alert = new OAlert(getContext());
										alert.setOK("确认");
										alert.setCancel("取消");
										alert.setTitle(R.string.s_init_mobile);
										alert.show();
										alert.setListener(new OAlertListener() {

											@Override
											public boolean onOK(OAlert alert) {
												Intent intent = new Intent(
														activity,
														RegisterFirstStepActivity.class);
												intent.putExtra(
														Constant.IDENTITY_KEY_1,
														Constant.TYPE_UPDATE_MOBILE);
												startActivity(intent);
												return false;
											}

											@Override
											public boolean onCancel(OAlert alert) {
												return false;
											}
										});
									} else {
										OAlert alert = new OAlert(getContext());
										alert.setOK("确认");
										alert.setCancel("取消");
										alert.setTitle(R.string.s_init_paypassword);
										alert.show();
										alert.setListener(new OAlertListener() {

											@Override
											public boolean onOK(OAlert alert) {
												try {
													CommonUtility
															.confirmSendCode(
																	activity,
																	GlobalSettings.sUser.Mobile,
																	Constant.TYPE_RESET_PAY_PASSWORD);
												} catch (Exception e) {
													e.printStackTrace();
												}
												return false;
											}

											@Override
											public boolean onCancel(OAlert alert) {
												return false;
											}
										});
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}
				}), CommonUtility.params(new String[] { Constant.PARAM_API,
						Constant.PARAM_TOKEN }, new String[] {
						"Account.CheckInitPayPwd", GlobalSettings.sToken }));
	}

	private void payZhifubao() {
		AccountRechargeApplyRequest req = new AccountRechargeApplyRequest();
		req.Pay_Platform = GlobalSettings.PAY_PLATFORM_ALI;
		req.cost = mYue;
		req.token = GlobalSettings.sToken;
		req.spbill_create_ip = DeviceUtility.DeviceInfo.getLocalHostIp();
		AccountRechargeApplyTask task = new AccountRechargeApplyTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<AccountRechargeApplyTask.AccountRechargeApplyRequest, AccountRechargeApplyTask.AccountRechargeApplyResponse>() {
			@Override
			public void onException(
					INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
					Exception e) {
				e.printStackTrace();
			}

			@Override
			public void onComplete(
					INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
					AccountRechargeApplyResponse response) {
				if (response.ResultCode != 200) {
					mPayWeixin.setEnabled(true);
					return;
				}
				doAliPay(response.Res.Order.OrderID);
				mPayWeixin.setEnabled(true);
			}
		});
		add(task);
	}

	private void payWeixin() {
		// 微信支付文档中所说的partnerId 对应于 接口返回值里的mch_id
		// 微信支付文档中所说的prepayId对应于 接口返回值里的prepay_id
		// 微信支付文档中所说的nonceStr对应于 接口返回值里的nonce_str
		// 微信支付文档中所说的sign对应于 接口返回值里的sign
		AccountRechargeApplyRequest req = new AccountRechargeApplyRequest();
		req.Pay_Platform = GlobalSettings.PAY_PLATFORM_WEIXIN;
		req.cost = mYue;
		req.token = GlobalSettings.sToken;
		req.spbill_create_ip = DeviceUtility.DeviceInfo.getLocalHostIp();
		AccountRechargeApplyTask task = new AccountRechargeApplyTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<AccountRechargeApplyTask.AccountRechargeApplyRequest, AccountRechargeApplyTask.AccountRechargeApplyResponse>() {

			@Override
			public void onException(
					INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
					Exception e) {
				e.printStackTrace();
			}

			@Override
			public void onComplete(
					INetTask<AccountRechargeApplyRequest, AccountRechargeApplyResponse> task,
					AccountRechargeApplyResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				try {
					JSONObject object = new JSONObject(JsonUtil
							.convert(response.Res.WeiXinXMLRes));
					if (!CommonUtility.isNull(object)
							&& object.getString("return_code")
									.equals("SUCCESS")) {
						IWXAPI api = WXAPIFactory.createWXAPI(getContext(),
								ShareWXUtils.APP_ID, false);
						boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
						if (isPaySupported) {
							PayReq req = new PayReq();
							req.appId = ShareWXUtils.APP_ID;
							req.partnerId = object.getString("partnerId");
							req.prepayId = object.getString("prepayId");
							req.nonceStr = object.getString("nonceStr");
							req.timeStamp = object.getString("timeStamp");
							req.packageValue = object.getString("packageValue");
							req.sign = object.getString("sign");
							api.sendReq(req);
						} else {
							toast("您当前微信版本不支持支付功能，请下载最新版本进行更新");
						}
					} else {
						toast("支付请求失败");
					}

				} catch (Exception e) {
					e.printStackTrace();
					mPayWeixin.setEnabled(true);
					toast("支付请求失败");
				}
			}
		});
		add(task);
	}

	protected void doAliPay(String outTradeNo) {
		AlipayTask task = new AlipayTask();
		task.setContext(this);
		task.setPartner(GlobalSettings.ALI_PAY_PARTNER);
		task.setSeller(GlobalSettings.ALI_PAY_SELLER);
		task.setRsaPrivate(GlobalSettings.ALI_PAY_PRIVATE_KEY);
		task.setOutTradeNo(outTradeNo);
		task.setSubject("皮肤科医生");
		task.setBody("皮肤科医生");
		task.setTotalFee(mYue + "");
		task.setNotifyUrl(GlobalSettings.ALI_PAY_NOTIFY_URL);
		task.addListener(new AlipayListener() {

			@Override
			public void onStop(AlipayTask task) {

			}

			@Override
			public void onStart(AlipayTask task) {

			}

			@Override
			public void onException(AlipayTask task, Exception e) {
				e.printStackTrace();
				OAlert alert = new OAlert(getContext());
				alert.setCancelable(false);
				alert.setOK("确认");
				alert.setTitle("支付失败");
				alert.setListener(new OAlert.OAlertListener() {

					@Override
					public boolean onDismiss(OAlert alert) {
						// finish();
						return false;
					}

					@Override
					public boolean onOK(OAlert alert) {
						return false;
					}

					@Override
					public boolean onCancel(OAlert alert) {
						return false;
					}
				});
				alert.show();
			}

			@Override
			public void onComplete(AlipayTask task) {
				Intent data = new Intent(Constant.RECEIVER_ACCOUNT_CHONGZHI);
				sendBroadcast(data);
				OAlert alert = new OAlert(getContext());
				alert.setCancelable(false);
				alert.setOK("确认");
				alert.setTitle("支付成功");
				alert.setListener(new OAlert.OAlertListener() {

					@Override
					public boolean onDismiss(OAlert alert) {
						Intent i = new Intent();
						setResult(0, i);
						finish();
						return false;
					}

					@Override
					public boolean onOK(OAlert alert) {
						return false;
					}

					@Override
					public boolean onCancel(OAlert alert) {
						return false;
					}
				});
				alert.show();
			}
		});
		task.start();
	}

	public void onClick(View view) {
		super.onClick(view);
		if (view instanceof CheckBox) {
			CheckBox check = (CheckBox) view;
			if (!check.isChecked()) {
				check.setChecked(true);
			} else {
				int id = view.getId();
				if (id == R.id.check_1) {
					mCostType = 1;
					mCheck2.setChecked(false);
					mCheck3.setChecked(false);
					mYue = mUser.Cost;
					// mPayWeixin.setText(String.format(txt_zhifubao,
					// mUser.Cost));
					// mPayWeixin.setVisibility(View.GONE);
					// mPayZhifubao.setVisibility(View.VISIBLE);
					mPayYue.setVisibility(View.GONE);
				} else if (id == R.id.check_2) {
					mCostType = 2;
					mCheck1.setChecked(false);
					mCheck3.setChecked(false);
					mYue = mUser.Cost;
					// mPayWeixin.setText(String.format(txt_weixin,
					// mUser.Cost));
					// mPayWeixin.setVisibility(View.VISIBLE);
					// mPayZhifubao.setVisibility(View.GONE);
					mPayYue.setVisibility(View.GONE);
				} else if (id == R.id.check_3) {

					if (GlobalSettings.sYue < mUser.Cost) {
						toast("余额不足");
						mCheck3.setChecked(false);
					} else {
						mCostType = 3;
						mCheck2.setChecked(false);
						mCheck1.setChecked(false);
						// showbutton();
					}
				}
			}
		}

	}

	private void showbutton() {
		if (mUser.Cost <= mAccountYue) {
			// 不显示支付按钮
			mPayWeixin.setVisibility(View.GONE);
			mPayZhifubao.setVisibility(View.GONE);
			mPayYue.setVisibility(View.VISIBLE);
		} else {
			mYue = mUser.Cost - mAccountYue;
			mPayWeixin.setVisibility(View.VISIBLE);
			mPayZhifubao.setVisibility(View.VISIBLE);
			mPayYue.setVisibility(View.GONE);
			mPayWeixin.setText(String.format(txt_weixin, mYue));
			mPayZhifubao.setText(String.format(txt_zhifubao_shengyu, mYue));
		}
	}
	
	
	
/*
	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/

}
